package com.hupu.jrs.ui.post

import android.content.Context
import com.hupu.jrs.api.forum.ForumApi
import com.hupu.jrs.bean.UploadData
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.util.ToastUtil
import java.util.ArrayList
import javax.inject.Inject
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1
import rx.schedulers.Schedulers

/**
 * Created by sll on 2016/3/9.
 */
@PerActivity
class PostPresenter @Inject
constructor(private val mForumApi: ForumApi, private val mContext: Context) : PostContract.Presenter {

    private var mSubscription: Subscription? = null
    private var mPostView: PostContract.View? = null
    private var paths: ArrayList<String>? = ArrayList()
    private var uploadCount = 0

    override fun checkPermission(type: Int, fid: String, tid: String) {
        mSubscription = mForumApi.checkPermission(fid, tid,
                if (type == Constants.TYPE_POST) "threadPublish" else "threadReply")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Any> { permissionData ->
                    if (permissionData != null) {
                        if (permissionData.error != null) {
                            mPostView!!.renderError(permissionData.error)
                        } else if (SettingPrefUtil.isNeedExam(mContext)) {
                            mPostView!!.renderExam(permissionData.exam)
                        }
                    }
                }, Action1<Throwable> { throwable -> throwable.printStackTrace() })
    }

    override fun parse(paths: ArrayList<String>) {
        this.paths = paths
    }

    override fun comment(tid: String, fid: String, pid: String, content: String) {
        mPostView!!.showLoading()
        if (paths != null && !paths!!.isEmpty()) {
            val images = ArrayList<String>()
            mSubscription = Observable.from(paths!!)
                    .flatMap<UploadData> { s -> mForumApi.upload(s) }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<UploadData>() {
                        override fun onStart() {
                            uploadCount = 0
                            images.clear()
                        }

                        override fun onCompleted() {
                            uploadCount++
                            if (uploadCount == paths!!.size) {
                                addReply(tid, fid, pid, content, images)
                            }
                        }

                        override fun onError(e: Throwable) {
                            uploadCount++
                            if (uploadCount == paths!!.size) {
                                addReply(tid, fid, pid, content, images)
                            }
                        }

                        override fun onNext(uploadData: UploadData?) {
                            if (uploadData != null) {
                                for (info in uploadData!!.files) {
                                    images.add(info.requestUrl)
                                }
                            }
                        }
                    })
        } else {
            addReply(tid, fid, pid, content, null)
        }
    }

    private fun addReply(tid: String, fid: String, pid: String, content: String, imgs: List<String>?) {
        val buffer = StringBuilder(content)
        if (imgs != null) {
            for (url in imgs) {
                buffer.append("<br><br><img src=\"").append(url).append("\"><br><br>")
            }
        }
        println("buffer:" + buffer.toString())
        mSubscription = mForumApi.addReplyByApp(tid, fid, pid, buffer.toString())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(Action1<Any> { data ->
            mPostView!!.hideLoading()
            if (data != null) {
                if (data.error != null) {
                    ToastUtil.showToast(data.error.text)
                } else if (data.status === 200) {
                    ToastUtil.showToast("发送成功~")
                    mPostView!!.postSuccess()
                }
            } else {
                ToastUtil.showToast("您的网络有问题，请检查后重试")
            }
        }, Action1<Throwable> {
            mPostView!!.hideLoading()
            ToastUtil.showToast("您的网络有问题，请检查后重试")
        })
    }

    override fun post(fid: String, content: String, title: String) {
        mPostView!!.showLoading()
        if (paths != null && !paths!!.isEmpty()) {
            val images = ArrayList<String>()
            mSubscription = Observable.from(paths!!)
                    .flatMap<UploadData> { s -> mForumApi.upload(s) }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<UploadData>() {
                        override fun onStart() {
                            uploadCount = 0
                            images.clear()
                        }

                        override fun onCompleted() {
                            uploadCount++
                            if (uploadCount == paths!!.size) {
                                addPost(fid, content, title, images)
                            }
                        }

                        override fun onError(e: Throwable) {
                            uploadCount++
                            if (uploadCount == paths!!.size) {
                                addPost(fid, content, title, images)
                            }
                        }

                        override fun onNext(uploadData: UploadData?) {
                            if (uploadData != null) {
                                for (info in uploadData!!.files) {
                                    images.add(info.requestUrl)
                                }
                            }
                        }
                    })
        } else {
            addPost(fid, content, title, null)
        }
    }

    private fun addPost(fid: String, content: String, title: String, imgs: List<String>?) {
        val buffer = StringBuilder(content)
        if (imgs != null) {
            for (url in imgs) {
                buffer.append("<br><br><img src=\"").append(url).append("\"><br><br>")
            }
        }
        mSubscription = mForumApi.addThread(title, buffer.toString(), fid)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(Action1<Any> { data ->
            mPostView!!.hideLoading()
            if (data != null) {
                if (data.error != null) {
                    ToastUtil.showToast(data.error.text)
                } else if (data.status === 200) {
                    ToastUtil.showToast("发送成功~")
                    mPostView!!.postSuccess()
                }
            } else {
                ToastUtil.showToast("您的网络有问题，请检查后重试")
            }
        }, Action1<Throwable> {
            mPostView!!.hideLoading()
            ToastUtil.showToast("您的网络有问题，请检查后重试")
        })
    }

    fun attachView(view: PostContract.View) {
        mPostView = view
    }

    fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mPostView = null
    }
}
